const bodyParser = require('body-parser')
const JWT = require('jsonwebtoken')
let { list } = require('./mock')
// 用户列表
const userList = [{
	username: 'admin',
	password: 'admin123',
	nickname: '管理员-小张',
	role: 'admin',
	avator: "https://robohash.org/1231"
}, {
	username: 'test',
	password: 'test123',
	nickname: '追梦的人',
	role: 'user',
	avator: "https://robohash.org/000"
}]
module.exports = app => {
	app.use(bodyParser.json())
	app.post('/api/login', (req, res) => {
		// 获取用户密码
		const { username, password } = req.body;
		// 验证
		const user = userList.find(v => v.password === password && v.username === username);
		// 
		if (user) {
			res.send({
				code: 200,
				message: '登录成功， 欢迎' + user.nickname,
				data: {
					nickname: user.nickname,
					role: user.role,
					avator: user.avator,
					token: JWT.sign({
						nickname: user.nickname,
						role: user.role,
						avator: user.avator,
					}, '666666')
				}
			})
		} else {
			res.send({
				code: 403,
				message: "账户密码错误, 请重新登录",
				data: null
			})
		}
	})
	// 列表请求
	app.get('/api/list', (req, res) => {
		const { keyword } = req.query;
		if (keyword) {
			res.send({
				code: 200,
				data: list.filter(v => {
					return v.id.includes(keyword) || v.type.includes(keyword) || v.nickname.includes(keyword) || v.tel.includes(keyword) || v.address.includes(keyword)
				}),
				message: '数据获取成功！'
			})
		} else
			res.send({
				code: 200,
				data: list,
				message: '数据获取成功！'
			})
	})
	// 列表删除
	app.delete('/api/list', (req, res) => {
		// 1. 获取删除的id
		const { id } = req.query;
		// 2. 过滤
		list = list.filter(v => v.id !== id)
		// 3. 返回
		res.send({
			code: 200,
			message: '数据删除成功！！'
		})
	})

	// 列表选中删除
	app.delete('/api/list/selected', (req, res) => {
		// 1. 获取删除的id
		const { selectedID } = req.query;
		// 2. 过滤
		list = list.filter(v => !selectedID.includes(v.id))
		// 3. 返回
		res.send({
			code: 200,
			message: '数据删除成功！！'
		})
	})

	// 图表接口
	app.get('/api/list/echarts/type', (req, res) => {
		const o = {};

		list.forEach(v => {
			const type = v.type
			if (o[type]) {
				o[type]++
			} else {
				o[type] = 1
			}
		});

		res.send({
			code: 200,
			data: {
				list1: Object.keys(o),
				list2: Object.values(o)
			},
			message: '图表数据获取成功'
		})
	})

	app.post('/api/list/update', (req, res) => {
		const { id } = req.body;

		const item = list.find(v => v.id === id)

		// 对象合并
		Object.assign(item, req.body);

		res.send({
			code: 200,
			message: '修改成功'
		})
	})


	app.post('/api/list/add', (req, res) => {
		req.body.id = Math.random().toString().slice(2);
		list.unshift(req.body);
		res.send({
			code: 200,
			message: '添加成功！！！'
		})
	})
}